<template>
  <div ref="container"></div>
</template>
<script setup lang="ts">
import {
  ref,
  inject,
  onMounted,
  onBeforeUnmount,
  markRaw,
  onUpdated,
} from "vue";
import type { ECharts, EChartsOption } from "echarts";

// 获取echart挂载的DOM节点
const container = ref();
const myChart = ref<ECharts>();

// 通过 inject 接收Echarts
const Echarts = inject("$echarts");

// 或
// 通过Vue全局注册方式获取
// const {proxy}: any = getCurrentInstance();

const initEchartsOneFn = () => {
  // echarts初始化
  myChart.value = markRaw((Echarts as any).init(container.value));

  // 或
  // let myChart = proxy.$echarts.init(container.value);

  const option: EChartsOption = {
    // 自定义echarts图标相关配置
    title: {
      text: "ECharts 入门示例",
    },
    tooltip: { trigger: "axis" },
    xAxis: {
      type: "category",
      boundaryGap: true, // 坐标轴两边留白策略
      data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
    },
    yAxis: {},
    series: [
      {
        name: "销量",
        type: "line",
        data: [5, 20, 36, 10, 10, 20],
      },
    ],
  };

  myChart.value.setOption(option);
  // 根据页面大小自动响应图表大小
  window.addEventListener("resize", function () {
    if (myChart.value) {
      myChart.value?.resize();
    }
  });
};
onUpdated(() => {
  if (myChart.value) {
    myChart.value?.resize();
  }
});
onMounted(() => {
  initEchartsOneFn();
});

onBeforeUnmount(() => {
  // 销毁echarts实例
  const myChart = (Echarts as any).getInstanceByDom(container.value);
  myChart.dispose();
});
</script>
